<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button  class="filter-item" type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <!-- <el-input v-model="listQuery.searchMsg" placeholder="搜索内容" style="width: 200px;" class="filter-item filter-input" @keyup.enter.native="handleFilter" />
      <el-button  class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button> -->
      <el-button class="filter-item add" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline" @click="handleCreate">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="标识" align="center">
        <template slot-scope="scope">
          {{ scope.row.slug }}
        </template>
      </el-table-column>
      <el-table-column label="名称" width="280" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" prop="createdAt" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updatedAt" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          <span>{{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog :title="title" :visible.sync="dialogFormVisible" custom-class="rolesDialog">
      <el-form ref="dataForm" :rules="rules" :model="Form" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">

        <el-form-item label="名称" prop="name">
          <el-input v-model="Form.name" />
        </el-form-item>
        <el-form-item label="标识" prop="slug">
          <el-input v-model="Form.slug" />
        </el-form-item>
        <el-tabs type="border-card" v-if="dialogStatus!=='create'">
          <!--<el-tab-pane label="权限">-->
            <!--<a-tree-->
              <!--checkable-->
              <!--v-model="checkedKeys"-->
              <!--:show-line="true"-->
              <!--:defaultExpandAll="true"-->
              <!--:tree-data="parentName"-->
              <!--@select="onSelect"-->
              <!--@check="onCheck"-->
            <!--&gt;-->
            <!--</a-tree>-->
          <!--</el-tab-pane>-->
          <el-tab-pane label="菜单">
            <a-tree
              checkable
              v-model="checkedKeysMenu"
              :show-line="true"
              :defaultExpandAll="true"
              :tree-data="menuList"
              @check="onCheckM"
            >
            </a-tree>
          </el-tab-pane>

        </el-tabs>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import {List , Add, Update,Delete ,rolesAsMenuAdd,rolesAsMenuDelete,rolesAsMenuHasAll} from '@/api/admin/roles'
import {hasAll ,rolesAsPermissionsAdd,rolesAsPermissionsDelete,rolesAsPermissionsHasAllById} from '@/api/admin/permissions'
import {hasAllMenu} from '@/api/admin/menu'
import iniMenu from '@/utils/common'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  components: { Pagination },
  name: 'roles',

  data() {
    return {
      list: null,
      listLoading: true,
      total:0,
      listQuery: {
        page: 1,
        limit: 10,
        searchMsg:""
      },
      dialogFormVisible:false,
      dialogStatus:"create",
      title:"",
      rules:{
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        slug: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]

      },
      Form:{
        id:null,
        name:"",
        slug:"",
        permissions:null

      },
      roles:null,
      parentName:null,
      checkedKeys:[],
      menuList:null,
      checkedKeysMenu:[]
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      List(this.listQuery).then(response => {
        let list = response.data

        const data = list

        // this.list = data.filter(item => item.id !== 1); // 过滤掉 id 为 1 的项
        this.list = data
        // this.total = response.data.queryTotal
        // this.listQuery.page = response.data.page
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
      hasAll().then(response =>{
        this.parentName = iniMenu.iniMenuPermissions(response.data)
      })
      hasAllMenu().then(response=>{
        this.menuList = iniMenu.iniMenuMenu(response.data)
      })


    },
    getList() {
      this.listLoading = true
      List(this.listQuery).then(response => {
        let list = response.data
        const data = list
        this.list = data
        // this.total = response.data.queryTotal
        // this.listQuery.page = response.data.page
        setTimeout(() => {
          this.listLoading = false
        }, 0.3 * 1000)
      })
    },
    handleFilter(){
      //搜索
      this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
      this.fetchData()
    },
    handleCreate(){
      //新增
      this.dialogFormVisible = true
      this.title = "添加角色"
      this.dialogStatus ='create'
      this.Form={
        id:null,
        name:"",
        slug:"",

      }
      setTimeout(()=>{
        this.$refs['dataForm'].clearValidate();
      },300)
    },
      handleUpdate(row){
        //编辑
        this.dialogFormVisible = true
        this.title = "修改角色"
        this.dialogStatus ='update'
        this.Form={
          id:row.id,
          name:row.name,
          slug:row.slug,
          permissions:null
        }
        console.log(row)
        console.log(this.Form)
        rolesAsPermissionsHasAllById({'id':row.id}).then((response)=>{
          this.checkedKeys = []
          for(let i=0;i<response.data.length;i++){
            this.checkedKeys.push(response.data[i].permissionId)
          }
        })
        rolesAsMenuHasAll({RoleId:row.id}).then(response=>{
          this.checkedKeysMenu = []
          console.log(response.data)
          for(let i=0;i<response.data.length;i++){
            this.checkedKeysMenu.push(response.data[i].menuId)
          }
        })

    },
    handleDelete(row,index){
      //删除
      this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          Delete({id:row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
    },
    handleRefresh(){
      //列表刷新
      this.fetchData()
    },
    handleStatus(row){
      //更改状态
      console.log(row)
    },
    createData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Add(this.Form).then((response) => {

              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })

          })
        }
      })
    },
    updateData(){
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          Update(this.Form).then(() => {
              this.dialogFormVisible = false
              this.fetchData()
              this.$notify({
                title: 'Success',
                message: '修改成功',
                type: 'success',
                duration: 2000
              })
          })

        }
      })
    },
    onSelect(){

    },
    onCheck(key,e){
      console.log(key)
      console.log(this.Form)
      console.log(this.checkedKeys)

      console.log(e)
      let data = {
        "roleId": this.Form.id,
        "permissionId": e.node.value
      }
      let flag = false
      let arr = []
      for(let i=0;i<this.parentName.length;i++){
        if(e.node.value == this.parentName[i].value){
          flag = true
          if(e.checked){
            rolesAsPermissionsAdd(data).then(response=>{})
          }else{
            rolesAsPermissionsDelete(data).then(response=>{ })
          }
          if(this.parentName[i].children.length>0){
            for(let a =0;a<this.parentName[i].children.length;a++){
              // arr.push(this.parentName[i].children[a].key)
              if(e.checked){
                let item = {
                  "roleId": this.Form.id,
                  "permissionId": this.parentName[i].children[a].key
                }
                rolesAsPermissionsAdd(item).then(response=>{
                })
              }else{
                let item = {
                  "roleId": this.Form.id,
                  "permissionId": this.parentName[i].children[a].key
                }
                rolesAsPermissionsDelete(item).then(response=>{
                })
              }
            }
          }
        }
      }
      if(!flag){
        if(e.checked){
            rolesAsPermissionsAdd(data).then(response=>{})
          }else{
            rolesAsPermissionsDelete(data).then(response=>{ })
          }
      }
    },
    onCheckM(key ,e){
      console.log(key)
      console.log(this.Form)
      console.log(this.checkedKeys)

      console.log(e)


      let data = {
        "roleId": this.Form.id,
        "menuId": e.node.value
      }
      let flag = false
      let arr = []
      for(let i=0;i<this.menuList.length;i++){
        if(e.node.value == this.menuList[i].value){
          flag = true
          if(e.checked){
            rolesAsMenuAdd(data).then(response=>{})
          }else{
            rolesAsMenuDelete(data).then(response=>{ })
          }
          if(this.menuList[i].children.length>0){

            for(let a =0;a<this.menuList[i].children.length;a++){
              // arr.push(this.parentName[i].children[a].key)
              console.log(this.menuList[i].children)
              if(e.checked){
                let item = {
                  "roleId": this.Form.id,
                  "menuId": this.menuList[i].children[a].key
                }
                rolesAsMenuAdd(item).then(response=>{
                })
              }else{
                let item = {
                  "roleId": this.Form.id,
                  "menuId": this.menuList[i].children[a].key
                }
                rolesAsMenuDelete(item).then(response=>{
                })
              }
            }
          }
        }
      }
      if(!flag){
        if(e.checked){
          rolesAsMenuAdd(data).then(response=>{})
          }else{
            rolesAsMenuDelete(data).then(response=>{ })
          }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.filter-container{
  background: #fff;
  padding: 0 10px;
  .filter-item{
    margin: 10px 0;
  }
  .filter-input{
    margin-left:  20px;
  }
  .add{
    float: right;
  }
}
.el-dialog__wrapper{
  >>>.el-dialog__body{
    height: 600px;
    overflow: auto;
  }
}

</style>
